package com.gcloud.dropbox;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;

import com.dropbox.client2.DropboxAPI.UploadRequest;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.android.AuthActivity;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxFileSizeException;
import com.dropbox.client2.exception.DropboxIOException;
import com.dropbox.client2.exception.DropboxParseException;
import com.dropbox.client2.exception.DropboxPartialFileException;
import com.dropbox.client2.exception.DropboxServerException;
import com.dropbox.client2.exception.DropboxUnlinkedException;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.TokenPair;
import com.dropbox.client2.session.Session.AccessType;
import com.example.gcode.Archivos;
import com.example.gcode.DropBoxSyncronized;
import com.example.gcode.GCloudSingleton;
import com.example.gcode.R;

import com.gfilechooser.utils.FileUtils;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.services.drive.Drive;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class UploadDropBoxFileActivity extends Activity {
	private static String TAG = UploadDropBoxFileActivity.class.getSimpleName();
	private ProgressDialog pDialog;
	
	
	private static final int REQUEST_CODE = 100;

	/* DROP BOX THINGS */
	final static private String APP_KEY = "bx9eufdsdzpbxs5";
	final static private String APP_SECRET = "tz6vorkhj2xvfv1";
	private static boolean mLoggedIn;
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	DropboxAPI<AndroidAuthSession> mApi;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);
		
		
		 dropBoxAuthentication();
		 showChooser();
//		showFilesOnUi();
//		 listFiles();

	}

	

	

	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("jalskjdf", "guaro!!");
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	
		private void dropBoxAuthentication() {
		AndroidAuthSession session = buildSession();
		mApi = new DropboxAPI<AndroidAuthSession>(session);
		checkAppKeySetup();
		if (DropBoxSyncronized.mLoggedIn) {
			Log.i("v()", "is still logged");
			showChooser();
			
		} else {
			Log.i("DropBoxAuthentication()", "is not logged");
			mApi.getSession().startAuthentication(UploadDropBoxFileActivity.this);
		}
		setLoggedIn(mApi.getSession().isLinked());
		Log.i("DropBoxAuthentication", "Logged: "
				+ mApi.getSession().isLinked());
		showToast("Logged: " + mApi.getSession().isLinked());
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {		
		case REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					// Get the URI of the selected file
					final Uri uri = data.getData();
					try {
						// Create a file instance from the URI
						final File file = FileUtils.getFile(uri);
						showToast("File selected: " + file.getAbsolutePath());
//						 UploadDropboxFile uploadDropBoxFile = new
//						 UploadDropboxFile(
//						 UploadDropBoxFileActivity.this, mApi, "/", file);
//						 uploadDropBoxFile.execute();
//						UploadGoogleFile googleFile = new UploadGoogleFile(
//								service, Archivos.this, file);
//						googleFile.execute();
						CargarArchivos uploadFile=new CargarArchivos();
						uploadFile.setFile(file);
						uploadFile.execute();
					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		// case REQUEST_CONFIRMATION:
		// startActivityForResult(credential.newChooseAccountIntent(),
		// REQUEST_ACCOUNT);
		// break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mApi.getSession() == null) {
			Log.i("onResume()", "session null");
			return;
		}
		AndroidAuthSession session = mApi.getSession();

		if (session.authenticationSuccessful()) {
			try {
				session.finishAuthentication();
				TokenPair tokens = session.getAccessTokenPair();
				storeKeys(tokens.key, tokens.secret);
				setLoggedIn(true);
			} catch (IllegalStateException e) {
				showToast("Couldn't authenticate with Dropbox:"
						+ e.getLocalizedMessage());
				Log.i(TAG, "Error authenticating", e);
			}
		}
	}

	

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void checkAppKeySetup() {
		if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
			showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the GCloud ap before trying it.");
			return;
		}
		Intent testIntent = new Intent(Intent.ACTION_VIEW);
		String scheme = "db-" + APP_KEY;
		String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
		testIntent.setData(Uri.parse(uri));
		PackageManager pm = getPackageManager();
		if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
			showToast("URL scheme in your app's "
					+ "manifest is not set up correctly. You should have a "
					+ "com.dropbox.client2.android.AuthActivity with the "
					+ "scheme: " + scheme);
		}
	}

	public AndroidAuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
		AndroidAuthSession session;

		String[] stored = getKeys();
		if (stored != null) {
			Log.i("buildSession", " getting key stored:");
			AccessTokenPair accessToken = new AccessTokenPair(stored[0],
					stored[1]);
			session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX,
					accessToken);
		} else {
			Log.i("buildSession",
					"getting key not stored, going to build a new one");
			session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX);
		}
		if (session != null) {
			Log.i("buildSession", " session is not null");
		}
		return session;
	}

	public String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}

	public void setLoggedIn(boolean loggedIn) {
		DropBoxSyncronized.mLoggedIn = loggedIn;
		Log.i("setLoggedIn() ", String.valueOf(mLoggedIn));
	}

	public void storeKeys(String key, String secret) {
		// Save the access key for later
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(ACCESS_KEY_NAME, key);
		edit.putString(ACCESS_SECRET_NAME, secret);
		edit.commit();
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(UploadDropBoxFileActivity.this);
			pDialog.setMessage("subiendo archivo ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		

		GCloudSingleton gCloudSingleton;	
		private String mErrorMsg;
		private String mPath="/";
		private UploadRequest mRequest;
		private File mFile;
		private long mFileLen;
		
		protected void setFile(String pathFile){
			File file = new File(pathFile);
			mFileLen = file.length();
			mFile = file;
		}
		
		protected void setFile(File file){			
			mFileLen = file.length();
			mFile = file;
		}
		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... voids) {

			try {
				// By creating a request, we get a handle to the putFile operation,
				// so we can cancel it later if we want to
				FileInputStream fis = new FileInputStream(mFile);
				String path = mPath + mFile.getName();
				mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
						new ProgressListener() {
							@Override
							public long progressInterval() {
								// Update the progress bar every half-second or so
								return 500;
							}

							@Override
							public void onProgress(long bytes, long total) {
								//setProgress((int) bytes);
							}
						});

				if (mRequest != null) {
					mRequest.upload();
					return "true";
				}

			} catch (DropboxUnlinkedException e) {
				// This session wasn't authenticated properly or user unlinked
				mErrorMsg = "This app wasn't authenticated properly.";
			} catch (DropboxFileSizeException e) {
				// File size too big to upload via the API
				mErrorMsg = "This file is too big to upload";
			} catch (DropboxPartialFileException e) {
				// We canceled the operation
				mErrorMsg = "Upload canceled";
			} catch (DropboxServerException e) {
				// Server-side exception. These are examples of what could happen,
				// but we don't do anything special with them here.
				if (e.error == DropboxServerException._401_UNAUTHORIZED) {
					// Unauthorized, so we should unlink them. You may want to
					// automatically log the user out in this case.
				} else if (e.error == DropboxServerException._403_FORBIDDEN) {
					// Not allowed to access this
				} else if (e.error == DropboxServerException._404_NOT_FOUND) {
					// path not found (or if it was the thumbnail, can't be
					// thumbnailed)
				} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
					// user is over quota
				} else {
					// Something else
				}
				// This gets the Dropbox error, translated into the user's language
				mErrorMsg = e.body.userError;
				if (mErrorMsg == null) {
					mErrorMsg = e.body.error;
				}
			} catch (DropboxIOException e) {
				// Happens all the time, probably want to retry automatically.
				mErrorMsg = "Network error.  Try again.";
			} catch (DropboxParseException e) {
				// Probably due to Dropbox server restarting, should retry
				mErrorMsg = "Dropbox error.  Try again.";
			} catch (DropboxException e) {
				// Unknown error
				mErrorMsg = "Unknown error.  Try again.";
			} catch (FileNotFoundException e) {
			}
			return "false";
			
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			if(file_url.equalsIgnoreCase("true")){
			showToast("everything well done");
			Intent newIntent=new Intent(UploadDropBoxFileActivity.this, Archivos.class);
			startActivity(newIntent);
			}else{
				showToast("probably something goes wrong");	
			}
			// if(){
//			 startActivityForResult(credential.newChooseAccountIntent(),
//			 REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread
			

		}

	}

}